package com.petdog.module.pet.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.common.dto.PageResult;
import com.petdog.infrastructure.entity.Pet;
import com.petdog.module.pet.dto.PetCreateRequest;
import com.petdog.module.pet.dto.PetDetailResponse;
import com.petdog.module.pet.dto.PetUpdateRequest;
import com.petdog.module.pet.service.PetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.Principal;

/**
 * 宠物控制器
 * 提供宠物相关的API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/pets")
public class PetController {
    
    @Autowired
    private PetService petService;
    
    /**
     * 创建宠物档案
     * 支持完整填写或暂存基本信息
     */
    @PostMapping(consumes = {"multipart/form-data", "application/json"})
    public ResponseEntity<ApiResponse<Pet>> createPet(
            @RequestPart(required = false) PetCreateRequest request,
            @RequestPart(required = false) MultipartFile photo,
            Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 如果没有提供request，则创建一个空的
            if (request == null) {
                request = new PetCreateRequest();
            }
            
            // 创建宠物档案
            Pet createdPet = petService.createPet(request, userId);
            
            // 如果上传了照片，单独更新照片
            if (photo != null) {
                createdPet = petService.updatePetPhoto(createdPet.getPetId(), photo, userId);
            }
            
            // 返回成功响应
            ApiResponse<Pet> response = ApiResponse.success(createdPet, "创建宠物档案成功");
            return new ResponseEntity<>(response, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            log.warn("创建宠物档案参数错误: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } catch (IOException e) {
            log.error("上传宠物照片失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("照片上传失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("创建宠物档案失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 获取宠物详情
     */
    @GetMapping("/{petId}")
    public ResponseEntity<ApiResponse<PetDetailResponse>> getPetDetail(@PathVariable Long petId, Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 获取宠物详情
            PetDetailResponse petDetail = petService.getPetDetail(petId, userId);
            
            if (petDetail == null) {
                ApiResponse<PetDetailResponse> response = ApiResponse.error("宠物不存在或无权限访问");
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }
            
            // 返回成功响应
            ApiResponse<PetDetailResponse> response = ApiResponse.success(petDetail, "获取宠物详情成功");
            return ResponseEntity.ok(response);
        } catch (SecurityException e) {
            log.warn("无权限访问宠物详情: {}", e.getMessage());
            ApiResponse<PetDetailResponse> response = ApiResponse.error("无权限操作该宠物");
            return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
        } catch (Exception e) {
            log.error("获取宠物详情失败: {}", e.getMessage());
            ApiResponse<PetDetailResponse> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 分页获取用户的宠物列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<PageResult<Pet>>> getUserPets(
            Principal principal,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 获取用户的所有宠物（分页）
            PageResult<Pet> pageResult = petService.getUserPets(userId, pageNum, pageSize);
            
            // 返回成功响应
            ApiResponse<PageResult<Pet>> response = ApiResponse.success(pageResult, "获取宠物列表成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取宠物列表失败: {}", e.getMessage());
            ApiResponse<PageResult<Pet>> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 更新宠物信息
     */
    @PutMapping(value = "/{petId}", consumes = {"multipart/form-data", "application/json"})
    public ResponseEntity<ApiResponse<Pet>> updatePet(
            @PathVariable Long petId,
            @RequestPart(required = false) PetUpdateRequest request,
            @RequestPart(required = false) MultipartFile photo,
            Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 如果没有提供request，则创建一个空的
            if (request == null) {
                request = new PetUpdateRequest();
            }
            
            // 更新宠物信息
            Pet updatedPet = petService.updatePet(petId, request, userId);
            
            // 如果上传了照片，单独更新照片
            if (photo != null) {
                updatedPet = petService.updatePetPhoto(updatedPet.getPetId(), photo, userId);
            }
            
            // 返回成功响应
            ApiResponse<Pet> response = ApiResponse.success(updatedPet, "更新宠物信息成功");
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("更新宠物信息参数错误: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } catch (SecurityException e) {
            log.warn("无权限更新宠物信息: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("无权限操作该宠物");
            return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
        } catch (IOException e) {
            log.error("上传宠物照片失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("照片上传失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("更新宠物信息失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 删除宠物档案
     */
    @DeleteMapping("/{petId}")
    public ResponseEntity<ApiResponse<Void>> deletePet(@PathVariable Long petId, Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 删除宠物档案
            petService.deletePet(petId, userId);
            
            // 返回成功响应
            ApiResponse<Void> response = ApiResponse.success(null, "删除宠物档案成功");
            return ResponseEntity.ok(response);
        } catch (SecurityException e) {
            log.warn("无权限删除宠物档案: {}", e.getMessage());
            ApiResponse<Void> response = ApiResponse.error("无权限操作该宠物");
            return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
        } catch (IllegalStateException e) {
            log.warn("宠物存在未完成业务，无法删除: {}", e.getMessage());
            ApiResponse<Void> response = ApiResponse.error("请先完成订单");
            return new ResponseEntity<>(response, HttpStatus.CONFLICT);
        } catch (Exception e) {
            log.error("删除宠物档案失败: {}", e.getMessage());
            ApiResponse<Void> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 单独更新宠物照片
     */
    @PostMapping("/{petId}/photo")
    public ResponseEntity<ApiResponse<Pet>> updatePetPhoto(
            @PathVariable Long petId,
            @RequestPart MultipartFile photo,
            Principal principal) {
        try {
            // 获取当前登录用户的ID
            Long userId = Long.parseLong(principal.getName());
            
            // 更新宠物照片
            Pet updatedPet = petService.updatePetPhoto(petId, photo, userId);
            
            // 返回成功响应
            ApiResponse<Pet> response = ApiResponse.success(updatedPet, "更新宠物照片成功");
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("更新宠物照片参数错误: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error(e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } catch (SecurityException e) {
            log.warn("无权限更新宠物照片: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("无权限操作该宠物");
            return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
        } catch (IOException e) {
            log.error("上传宠物照片失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("照片上传失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("更新宠物照片失败: {}", e.getMessage());
            ApiResponse<Pet> response = ApiResponse.error("系统异常，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
